from django.shortcuts import render, reverse
from django.http import request, HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
import json

# Create your views here.

def signin(request):
    if request.method == 'GET':
        return render(request, 'Znd_class/signin.html')
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return HttpResponse(json.dumps({
                "status": 20,
                "msg": "登陆成功!",
                "url": reverse('Znd_class:index')
            }))
        else:
            return HttpResponse(json.dumps({
                "status": 21,
                "msg": "用户名或密码错误",
                "url": reverse('Znd_class:signin')
            }))

@login_required
def index(request):
    current_user = request.user
    if current_user.is_student:
        return HttpResponseRedirect(reverse('Znd_class:student'))
    else:
        return HttpResponseRedirect(reverse('Znd_class:admin'))

@login_required
def admin_page(request):
    return render(request, 'Znd_class/admin.html')

@login_required
def student(request):
    return render(request, 'Znd_class/student.html')

